package gl.java.util;

import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class ConnectionPool<K,V> {

	private Map<Channel, K> mChannelMap;
	private Map<K, Channel> mKeyMap;
	private Map<K, V> mValueMap;

	public ConnectionPool() {
		mChannelMap = new ConcurrentHashMap<Channel, K>();
		mKeyMap = new ConcurrentHashMap<K, Channel>();
        mValueMap = new ConcurrentHashMap<K, V>();
	}
	public V remove(Channel ctx) {
		if (ctx == null) {
			return null;
		}
		if (mChannelMap.containsKey(ctx)) {
            K key = mChannelMap.remove(ctx);
            if (key!=null&&mKeyMap.containsKey(key)&&mValueMap.containsKey(key)) {
                mKeyMap.remove(key);
                return mValueMap.remove(key);
            }
		}
		return null;

	}

	/**
	 * 通过value遍历查找key
	 * 
	 * @param key key
	 * @return channel
	 */
	public Channel getConnectionChannel(K key) {
		return mKeyMap.get(key) ;
	}



	public void put(K key, Channel ctx,V v) {
		mChannelMap.put(ctx, key);
		mKeyMap.put(key, ctx);
		mValueMap.put(key,v);
	}


	public V getObject(Channel ctx) {
		final K userID = mChannelMap.get(ctx);
		return mValueMap.get(userID);
	}



	public K getKey(Channel ctx) {
		return mChannelMap.get(ctx);
	}

	public List<Channel> toConnectionList(){
		final ArrayList<Channel> arrayList = new ArrayList<Channel>();
		Set<K> keySet = mKeyMap.keySet();
		for (K integer : keySet) {
			arrayList.add(mKeyMap.get(integer));
		}
		return arrayList;
	}
}
